extends CharacterBody2D
class_name BaseEnemy

@onready var hit_box: Area2D = $HitBox

@export var speed = 50.0
@export var max_health = 10
@export var damage = 5
@export var experience_value = 1
@export var attack_cooldown = 1.0
@export var knockback_resistance = 5.0  # 每秒减少的击退量

var health = max_health
var player = null
var time_to_next_attack = 0
var difficulty_modifier = 1.0
var knockback_vector = Vector2.ZERO  # 击退向量
var is_being_knocked_back = false    # 是否正在被击退
var knockback_time = 0.0             # 击退状态持续时间
var pickup_manager = null            # 拾取物品管理器引用

func _ready():
	# 获取玩家引用
	player = get_node("/root/Main/World/Player")
	health = max_health
	
	# 尝试获取PickupManager引用
	pickup_manager = get_node_or_null("/root/Main/World/PickupManager")
	if pickup_manager == null:
		pickup_manager = get_node_or_null("/root/Main/PickupManager")
	
	# 设置碰撞层和掩码
	# 物理碰撞（用于与环境和其他敌人碰撞）
	set_collision_layer(16)  # 第5层：敌人物理层
	set_collision_mask(1|2|16)   # 第1、2、5层：玩家物理层、环境层、敌人物理层
	
	# 将敌人添加到组便于管理
	hit_box.add_to_group("enemy_hitbox")
	
	# 连接伤害检测信号
	hit_box.connect("area_entered", _on_hitbox_area_entered)
	
	hit_box.set_collision_layer(8)    # 第4层：敌人攻击层
	hit_box.set_collision_mask(32)    # 第6层：玩家子弹层
	

func get_damage():
	return damage

func initialize(difficulty = 1.0):
	# 根据难度调整敌人属性
	difficulty_modifier = difficulty
	max_health = int(max_health * difficulty_modifier)
	health = max_health
	damage = int(damage * difficulty_modifier)
	speed = speed * (1 + (difficulty_modifier - 1) * 0.5)  # 速度增长较慢
	
	# 难度也会影响经验值
	experience_value = int(experience_value * sqrt(difficulty_modifier))

func _physics_process(delta):
	if player == null or health <= 0:
		return
	
	# 处理击退状态
	if is_being_knocked_back:
		knockback_time -= delta
		if knockback_time <= 0:
			is_being_knocked_back = false
			knockback_vector = Vector2.ZERO
		else:
			# 移动敌人（应用击退）
			velocity = knockback_vector
			move_and_slide()
			return
	
	# 正常移动（只有在不被击退时执行）
	var direction = (player.global_position - global_position).normalized()
	velocity = direction * speed
	move_and_slide()
	
	# 处理攻击冷却
	if time_to_next_attack > 0:
		time_to_next_attack -= delta

#func attack_player():
	#if player.has_method("take_damage"):
		#player.take_damage(damage)

# 当HitBox（伤害检测区域）检测到敌人攻击时
func _on_hitbox_area_entered(area):
	var projectile = area.get_parent()
	var damage = projectile.get_damage() if projectile.has_method("get_damage") else 0
	
	# 获取击退力度并应用
	if projectile.has_method("get_knockback"):
		var knockback_force = projectile.get_knockback()
		var knockback_direction = (global_position - projectile.global_position).normalized()
		take_knockback(knockback_direction * knockback_force,0.3)
	
	projectile.queue_free()
	take_damage(damage)

func take_knockback(knockback_vector,knockback_time):
	self.knockback_vector = knockback_vector
	is_being_knocked_back = true
	self.knockback_time = knockback_time

func take_damage(amount):
	health -= amount
	
	# 播放受伤效果
	modulate = Color(1, 0.5, 0.5)  # 变红
	await get_tree().create_timer(0.1).timeout
	modulate = Color(1, 1, 1)  # 恢复正常颜色
	
	if health <= 0:
		die()

func die():
	# 生成经验宝石
	if pickup_manager != null and pickup_manager.has_method("spawn_experience"):
		pickup_manager.spawn_experience(global_position, experience_value)
	else:
		# 如果没有PickupManager，退回到直接增加经验值
		var game_manager = get_node_or_null("/root/Main/GameManager")
		if game_manager and game_manager.has_method("add_experience"):
			game_manager.add_experience(experience_value)
	
	# 随机概率生成其他物品（例如金币、生命药水）
	if pickup_manager != null:
		# 5%的几率掉落生命药水
		if randf() < 0.05:
			pickup_manager.spawn_health_potion(global_position)
	
	# 播放死亡动画或效果
	# 可以添加粒子效果、声音等
	
	# 从场景中移除
	queue_free() 
